package edu.uwlax.cs.oayonlinestore.client.utils;

import java.util.Date;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import edu.uwlax.cs.oayonlinestore.client.utils.FormTable.Enablebar;
import edu.uwlax.cs.oayonlinestore.exceptions.UserInputException;

public class DateEdit extends HorizontalPanel implements Enablebar {

	private class NowHandler implements ClickListener {
		public void onClick(Widget arg0) {
			setDate(new Date());
		}
	}

	public final static int PREC_DAY = 2;

	public final static int PREC_MONTH = 1;

	public final static int PREC_YEAR = 0;

	private TextBox day;

	private TextBox month;

	private Button nowBtn;

	private TextBox year;

	public DateEdit(boolean showDay, boolean showNowBtn) {
		super();
		year = new TextBox();
		month = new TextBox();
		year.setWidth("48px");
		month.setWidth("32px");
		add(year);
		add(month);
		if (showDay) {
			day = new TextBox();
			day.setWidth("32px");
			add(day);
		}
		if (showNowBtn)
			add(nowBtn = new Button("now", new NowHandler()));
	}

	public static class InvalidDateException extends Exception {

		public InvalidDateException(String message) {
			super(message);
		}
	}

	public Date getDate() throws InvalidDateException {
		int y = Integer.parseInt(year.getText()) - 1900;
		int m = Integer.parseInt(month.getText()) - 1;
		int d = (day == null) ? 1 : Integer.parseInt(day.getText());
		if ((y < 0) || (y > 200))
			throw new InvalidDateException(
					"The year must be between 1900 and 2100.");
		if ((m < 0) || (m > 11))
			throw new InvalidDateException(
					"The month must be between 1 and 12.");
		if ((d < 1) || (d > 31))
			throw new InvalidDateException("The day must be between 1 and 31.");
		return new Date(y, m, d);
	}

	public void setDate(Date d) {
		if (d == null)
			d = new Date();
		year.setText(String.valueOf(d.getYear() + 1900));
		month.setText(String.valueOf(d.getMonth() + 1));
		if (day != null)
			day.setText(String.valueOf(d.getDay()));
	}

	public void setEnabled(boolean val) {
		year.setEnabled(val);
		month.setEnabled(val);
		if (day != null)
			day.setEnabled(val);
		if (nowBtn != null)
			nowBtn.setEnabled(val);
	}

}
